# -*- coding: utf8-*-
import xlwt, xlrd
import json
import sys

from datetime import timedelta

import logging
import datetime
import Config
import ArgsParse

logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',level=1)

workDayasHoliday = []
holidayasWorkDay = []


def isworkDayasHoliday(m_date):
    '''check whether one day is work day as a holiday'''
    print "workdayasholiday is:",workDayasHoliday
    print "m_date", m_date
    print m_date in workDayasHoliday
    if m_date in workDayasHoliday:
        return True
    return False

def isholidayasWorkDay(m_date):
    '''check whether one day is holiday as workday'''
    print "holidayasworkday is:",holidayasWorkDay
    print "m_date",m_date
    if(m_date in holidayasWorkDay):
        return True
    return False


def getAllWorkDay(startDate,endDate):
    '''get all work day from startDate to endDate'''
    global  workDayasHoliday,holidayasWorkDay
    logging.info("get all workdays from %s to %s"%(startDate,endDate))
    workDayasHoliday, holidayasWorkDay = ArgsParse.parse()

    print workDayasHoliday, holidayasWorkDay
    days_work = [x for x in range(5)]
    allworkdays = []
    fromDate = startDate
    while True:
        if(fromDate>endDate):
            break
        if fromDate.weekday() in days_work and not isworkDayasHoliday(fromDate.strftime('%Y/%m/%d')):        #day is in Monday to Friday and not holiday
                allworkdays.append(fromDate.strftime('%Y/%m/%d'))
        fromDate += datetime.timedelta(days=1)

    for day in holidayasWorkDay:
        print "aaaa",day
        day = datetime.datetime.strptime(day, "%Y/%m/%d").date()
        if day >= startDate and day <= endDate:
            allworkdays.append(day.strftime('%Y/%m/%d'))
    allworkdays.sort()
    logging.info("all work days from %s to %s is %s"%(startDate,endDate,allworkdays))
    return allworkdays


def formatList(m_list):
    for i in range(len(m_list)-1):
        m_list[i] = m_list[i] + "\n"


class Utils:
    @classmethod
    def formatTime(cls,m_time):
        return datetime.datetime.strptime(m_time, "%Y/%m/%d %H:%M:%S")

    @classmethod
    def formatDate(cls,m_date):
        return datetime.datetime.strptime(m_date, "%Y/%m/%d").date().strftime('%Y/%m/%d')

    @classmethod
    def formatList(cls,m_list):
        for i in range(len(m_list) - 1):
            m_list[i] = m_list[i] + "\n"


class ExcelStyle:
    def __init__(self):

        self.style = xlwt.XFStyle()
        alignment = xlwt.Alignment()  # Create Alignment
        alignment.wrap = 1
        alignment.horz = xlwt.Alignment.HORZ_LEFT  # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
        alignment.vert = xlwt.Alignment.VERT_CENTER  # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
        self.style.alignment = alignment

        self.pattern = "PatternA"


    def setPattern(self):
        if self.pattern == "PatternA":
            pattern = xlwt.Pattern()
            pattern.pattern = xlwt.Pattern.NO_PATTERN  # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
            #pattern.pattern_fore_colour = 0
            self.style.pattern = pattern
            self.pattern = "PatternB"

        elif self.pattern == "PatternB":
            pattern = xlwt.Pattern()
            pattern.pattern = xlwt.Pattern.SOLID_PATTERN
            pattern.pattern_fore_colour = 22
            self.style.pattern = pattern
            self.pattern = "PatternA"



def writeToExcel(sheet,row,colum,value,style=""):

    if style=="":
        sheet.write(row, colum, value)
    else:
        sheet.write(row,colum,value,style)


def addSheet(book,sheetname):
    return book.add_sheet(sheetname,cell_overwrite_ok=True)
def creatNewBook():
    return xlwt.Workbook(encoding="utf-8",style_compression=0)



def readXls():

    logging.info("read excel file to get all the work record")
    xlsFile = r"D:\AttendanceRecord\201612.xlsx"
    book = xlrd.open_workbook(xlsFile,encoding_override="utf-8")
    sheetName = book.sheet_names()[0]
    #print sheetName
    sheet0 = book.sheet_by_index(0)

    allWorkRecordwithName = dict()
    workRecord = []
    nrows = sheet0.nrows

    ncols = sheet0.ncols

    recordList = []
    for row in range(1,nrows):
        name = sheet0.cell_value(row,1)
        if name not in allWorkRecordwithName.keys():

            if len(recordList)>0 and len(allWorkRecordwithName)>0:

                workRecord.append(recordList)
                allWorkRecordwithName[name] = workRecord
                recordList = []
            workRecord = []


        record = sheet0.cell_value(row,3)

        dateandtime = record.split(" ")
        time = dateandtime[0] +" "+dateandtime[1]

        time = Utils.formatTime(time)
        noonTime = dateandtime[0] +" "+ "13:00:00"
        noonTime = Utils.formatTime(noonTime)
        if(len(recordList) ==0):

                if(time > Utils.formatTime(dateandtime[0] +" "+ Config.OFF_TIME)):

                    recordList = [dateandtime[0],"",dateandtime[1]]
                else:
                    recordList = [dateandtime[0],dateandtime[1],""]




        elif(dateandtime[0] == recordList[0]):
            if(recordList[1]!=""):
                if  (time-Utils.formatTime(dateandtime[0] +" "+recordList[1])<timedelta(minutes=20)):

                    recordList[2] = ""
                else:
                    recordList[2] = dateandtime[1]

            else:
                recordList[2] = dateandtime[1]
        else:

            workRecord.append(recordList)

            allWorkRecordwithName[name] = workRecord
            recordList = []
            if (time > Utils.formatTime(dateandtime[0] + " " + Config.OFF_TIME)):
                recordList = [dateandtime[0], "", dateandtime[1]]
            else:
                recordList = [dateandtime[0], dateandtime[1], ""]

    if (len(recordList) > 0 and len(allWorkRecordwithName) > 0):
        workRecord.append(recordList)
        allWorkRecordwithName[name] = workRecord

    for key,value in allWorkRecordwithName.items():
        logging.info("%s:%s"%(key,value))

    return allWorkRecordwithName

def readXls_new():
    xlsFile = r"kaoqin.xlsx"
    book = xlrd.open_workbook(xlsFile,encoding_override="utf-8")
    sheetName = book.sheet_names()[0]
    #print sheetName
    sheet0 = book.sheet_by_index(0)

    allWorkRecordwithName = {}
    workRecord = []
    nrows = sheet0.nrows
    #print nrows
    ncols = sheet0.ncols

    recordList = []
    dateSet = set()
    nameIndex = getIndexFromColoumName(sheet0,"姓名")
    dateIndex = getIndexFromColoumName(sheet0,"日期")
    startIndex = getIndexFromColoumName(sheet0,"签到时间")
    endIndex = getIndexFromColoumName(sheet0,"签退时间")

    for row in range(1,nrows):

        #name = sheet0.cell_value(row,1)
        name = sheet0.cell_value(row, nameIndex)
        if name not in allWorkRecordwithName.keys():
            if(len(recordList)>0 and len(allWorkRecordwithName)>0):
                workRecord.append(recordList)
                allWorkRecordwithName[name] = workRecord
                recordList = []
            workRecord = []
        #the first person
        #date = sheet0.cell_value(row,2)
        date = sheet0.cell_value(row, dateIndex)
        dateSet.add(date)
        #start_time = sheet0.cell_value(row,5)
        start_time = sheet0.cell_value(row, startIndex)
        start_time = start_time + ":00" if len(start_time)>0 else  ""


        #end_time = sheet0.cell_value(row,6)
        end_time = sheet0.cell_value(row, endIndex)
        end_time = end_time + ":00" if len(end_time)>0 else  ""

        if start_time == "" and end_time == "":
            continue
        recordList.append(date)
        recordList.append(start_time)
        recordList.append(end_time)
        workRecord.append(recordList)

        allWorkRecordwithName[name]=workRecord
        recordList = []
        if (len(recordList) > 0 and len(allWorkRecordwithName) > 0):
            workRecord.append(recordList)
            allWorkRecordwithName[name] = workRecord
    print "all date in excel:",dateSet
    dateList = []
    for d in dateSet:
        dateList.append(Utils.formatDate(d))
    print "all dateList:",dateList
    print "sorted set:",sorted(dateSet)
    print "sorted list",sorted(dateList)
    print sorted(dateList)[0],sorted(dateList)[len(dateList)-1]
    return (sorted(dateList)[0],sorted(dateList)[len(dateList)-1],allWorkRecordwithName)

def getIndexFromColoumName(sheet,columnName):
    num_columns = sheet.ncols
    for index in range(0,num_columns):
        name = sheet.cell_value(0,index)

        if name == columnName.decode('utf-8'):
            return index
